package uk.co.richardwkirk.parkrun.data.events;

import uk.co.richardwkirk.parkrun.data.ParkrunDataLoadException;
import uk.co.richardwkirk.parkrun.web.ParkrunPageLoader;
import uk.co.richardwkirk.parkrun.web.ParkrunURLGenerator;
import uk.co.richardwkirk.parkrun.web.ParkrunWebConnection;
import uk.co.richardwkirk.parkrun.web.ParkrunWebException;
import uk.co.richardwkirk.parkrun.web.parsers.LatestResultsParser;
import uk.co.richardwkirk.parkrun.web.parsers.ParkrunDataParseException;

public class ParkrunEventFinder {

	ParkrunPageLoader pageLoader = null;
	ParkrunWebConnection parkrunWebConnection = new ParkrunWebConnection();
	
	public ParkrunEventFinder() {
		pageLoader = new ParkrunPageLoader();
	}
	
	public String getEventResultURL(String parkrunName, int eventNumber) throws ParkrunDataLoadException {
		// Check we have a valid parkrun
		if (!isValidUKParkrun(parkrunName)) {
			throw new ParkrunDataLoadException("This is not a valid UK parkrun: " + parkrunName);
		}
		
		// Check that the event should exist
		if (eventNumber <= 0 || eventNumber > latestEventNumber(parkrunName)) {
			throw new ParkrunDataLoadException("Event " + eventNumber + " has not occured at " + parkrunName + " parkrun.");
		}
		
		return ParkrunURLGenerator.createUKEventResultURL(parkrunName, eventNumber);
	}
	
	public boolean isValidUKParkrun(String parkrunName) throws ParkrunDataLoadException {
		try {
			return parkrunWebConnection.checkUKEventURLExists(parkrunName);
		} catch (ParkrunWebException e) {
			throw new ParkrunDataLoadException("Could not check validity on parkrun site.", e);
		}
	}
	
	public int latestEventNumber(String parkrunName) throws ParkrunDataLoadException {
		// Check we have a valid parkrun
		if (!isValidUKParkrun(parkrunName)) {
			throw new ParkrunDataLoadException("This is not a valid UK parkrun: " + parkrunName);
		}
		
		String latestEventURL = ParkrunURLGenerator.createLatestUKEventResultsURL(parkrunName);
		String latestEventPageContent;
		latestEventPageContent = pageLoader.load(latestEventURL);
		return parseLatestEventNumber(latestEventPageContent);
	}

	private int parseLatestEventNumber(String latestEventPageContent) throws ParkrunDataLoadException {
		try {
			LatestResultsParser parser = new LatestResultsParser(latestEventPageContent);
			return parser.getLatestParkrunNumber();
		} catch (ParkrunDataParseException e) {
			throw new ParkrunDataLoadException("Could not find latest event number.", e);
		}
		
	}
}
